import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Card,
  Form,
  Input,
  Button,
  Checkbox,
  message,
  Typography,
  Divider,
  Space,
} from 'antd';
import {
  UserOutlined,
  LockOutlined,
  HeartOutlined,
  MobileOutlined,
} from '@ant-design/icons';
import { useAuthStore, useAppStore } from '@/store';
import { authAPI } from '@/services/api';

const { Title, Text } = Typography;

interface LoginForm {
  account: string;
  password: string;
  remember: boolean;
}

const Login: React.FC = () => {
  const navigate = useNavigate();
  const { login } = useAuthStore();
  const { setLoading } = useAppStore();
  const [form] = Form.useForm();
  const [loginType, setLoginType] = useState<'account' | 'phone'>('account');

  const handleLogin = async (values: LoginForm) => {
    try {
      setLoading(true);
      
      // 调用登录API
      const response = await authAPI.login({
        account: values.account,
        password: values.password,
      });
      
      if (response.success) {
        const { user, token } = response.data;
        
        // 保存token
        if (values.remember) {
          localStorage.setItem('token', token);
          localStorage.setItem('user', JSON.stringify(user));
        }

        login(user);
        message.success('登录成功');
        navigate('/', { replace: true });
      } else {
        message.error(response.message || '登录失败');
      }
    } catch (error: any) {
      message.error(error.message || '登录失败，请检查账号密码');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '20px',
    }}>
      <Card
        style={{
          width: 400,
          boxShadow: '0 4px 20px rgba(0,0,0,0.1)',
        }}
        bodyStyle={{ padding: '40px' }}
      >
        <div style={{ textAlign: 'center', marginBottom: '32px' }}>
          <HeartOutlined
            style={{
              fontSize: '48px',
              color: '#722ed1',
              marginBottom: '16px',
            }}
          />
          <Title level={3} style={{ margin: 0, color: '#262626' }}>
            相亲平台管理系统
          </Title>
          <Text type="secondary">欢迎使用后台管理系统</Text>
        </div>

        <Form
          form={form}
          name="login"
          initialValues={{
            account: 'admin',
            password: '123456',
            remember: true,
          }}
          onFinish={handleLogin}
          size="large"
          autoComplete="off"
        >
          <Form.Item
            name="account"
            rules={[
              { required: true, message: '请输入账号或手机号' },
              loginType === 'phone'
                ? { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                : { min: 3, message: '账号至少3个字符' },
            ]}
          >
            <Input
              prefix={loginType === 'account' ? <UserOutlined /> : <MobileOutlined />}
              placeholder={loginType === 'account' ? '请输入账号' : '请输入手机号'}
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码至少6位' },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入密码"
            />
          </Form.Item>

          <Form.Item>
            <div style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住我</Checkbox>
              </Form.Item>
              <Button type="link" size="small">
                忘记密码?
              </Button>
            </div>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>

        <Divider>
          <Text type="secondary">或</Text>
        </Divider>

        <Space direction="vertical" style={{ width: '100%' }}>
          <Button
            block
            onClick={() => setLoginType(loginType === 'account' ? 'phone' : 'account')}
          >
            {loginType === 'account' ? '手机号登录' : '账号登录'}
          </Button>
          
          <div style={{ textAlign: 'center', marginTop: '16px' }}>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              测试账号：admin / 密码：123456
            </Text>
          </div>
        </Space>
      </Card>
    </div>
  );
};

export default Login;